from PySide6.QtCore import QIODevice, QObject, QTimer, Slot, Signal, Property
from PySide6.QtQml import QmlElement, QmlSingleton
from PySide6.QtSerialPort import QSerialPortInfo, QSerialPort
import logging

class SerialPortItem(QObject):
    def __init__(self, portName, desc, parent=None):
        super().__init__(parent)
        self._portName = portName
        self._desc = desc
        
    @Property(str, constant=True)
    def portName(self):
        return self._portName
    
    @Property(str, constant=True)
    def description(self):
        return self._desc

# 定义 QML 模块名称和版本
QML_IMPORT_NAME = "utils"
QML_IMPORT_MAJOR_VERSION = 1

@QmlElement
@QmlSingleton
class SerialPortInfo(QObject):
    serialPortsChanged = Signal()
    def __init__(self, parent=None):
        super().__init__(parent)
        
        self._serialPorts = []
        self._refreshPorts()
        
        # 设置定时器自动刷新端口列表
        self._timer = QTimer(self)
        self._timer.timeout.connect(self._refreshPorts)
        self._timer.start(2000)  # 每2秒刷新一次
    
    def _refreshPorts(self):
        new_ports = [SerialPortItem(port.portName(), port.description()) for port in QSerialPortInfo.availablePorts()]
        
        # 只有当端口列表真正改变时才发射信号
        if len(new_ports) != len(self._serialPorts) or any(np.portName != op.portName for np, op in zip(new_ports, self._serialPorts)):
            logging.info("Serial port list changed")
            self._serialPorts = new_ports
            self.serialPortsChanged.emit()
    
    
    @Property('QVariantList', notify=serialPortsChanged)
    def serialPorts(self):
        return self._serialPorts